using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ContentOverContainer.Common;
using ContentOverContainer.Common.Converter;
using Roslyn.Compilers.CSharp;

namespace ContentOverContainer.Converter
{
    public static class ConditionalExpressionConverter
    {
        public static ChangeNodeInfo ConvertConditionalExpression(ConditionalExpressionSyntax exprSyntax, ConverterContext pConverterData)
        {
            var falseValue = exprSyntax.WhenFalse; //e1 ? e2 : *e3*  -->> e3
            var falseValueName = falseValue as SimpleNameSyntax;
            var falseValueDecl = falseValueName.GetMemberDeclaration(pConverterData.SemanticModel);
            var falseValueMultiKind = falseValueDecl.GetMultiplicityKind();

            var trueValue = exprSyntax.WhenTrue; //e1 ? *e2* : e3  -->> e2
            var trueValueName = trueValue as SimpleNameSyntax;
            var trueValueDecl = trueValueName.GetMemberDeclaration(pConverterData.SemanticModel);
            var trueValueMultiKind = trueValueDecl.GetMultiplicityKind();
      
            if (trueValueMultiKind == MultiplicityKind.Any
                || falseValueMultiKind == MultiplicityKind.Any)
            {
                if (trueValueMultiKind != MultiplicityKind.Any)
                {//upcast true value
                    var collectionType = falseValueDecl.GetMultiplicityType() as GenericNameSyntax;
                    var casted = CastConverter.UpcastToAny(trueValue, trueValueDecl.GetDeclarationType(), trueValueName,
                                              collectionType.ToString());
                    casted.NewSyntaxNode = Syntax.ParseExpression(string.Format("{0}?{1}:{2}", exprSyntax.Condition,
                                                             casted.NewSyntaxNode, falseValue));
                    return casted;
                 
                }

                if (falseValueMultiKind != MultiplicityKind.Any)
                {//upcast false value
                    var collectionType = trueValueDecl.GetMultiplicityType() as GenericNameSyntax;
                    var casted = CastConverter.UpcastToAny(falseValue, falseValueDecl.GetDeclarationType(), falseValueName, collectionType.Identifier.ToString());
                    casted.NewSyntaxNode = Syntax.ParseExpression(string.Format("{0}?{1}:{2}", exprSyntax.Condition, trueValue, casted.NewSyntaxNode));
                    return casted;  
                }

            }

            return new ChangeNodeInfo(exprSyntax);
        }
    }
}
